<template>
  <div id="login">
    <div class="login_header">
      <h3 class="title">华医仕销售后台管理系统</h3>
    </div>

    <div class="login_content">
      <h3>欢迎登录</h3>
      <el-form
        ref="loginForm"
        :model="loginForm"
        status-icon
        :rules="rules"
        class="demo-loginForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            autocomplete="off"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            autocomplete="off"
            placeholder="请输入密码"
            show-password
            prefix-icon="el-icon-lock"
          />
        </el-form-item>
        <el-form-item prop="otp" class="kaptcha">
          <el-input
            v-model="loginForm.otp"
            type="text"
            autocomplete="off"
            placeholder="请输入验证码"
            prefix-icon="el-icon-coordinate"
          />
          <!-- <div class="kaptcha_img">
            <img
              :src="image"
              title="看不清? 换一张"
              alt="验证码加载失败"
              @click="handleOpt"
            />
          </div> -->
           <div class="ValidCode disabled-select" :style="`width:${width}; height:${height}`" @click="refreshCode">
    <span v-for="(item, index) in codeList" :key="index" :style="getStyle(item)">{{item.code}}</span>
  </div>
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            @click="submitForm('loginForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
// import { getKaptcha } from '../../api/common';
export default {
  name: "Login",
  props: {
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '40px'
    },
    length: {
      type: Number,
      default: 4
    }
  },
  data() {
    return {
      codeList: [],
      loginForm: {
        username: "",
        password: "",
        otp: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]+$/,
            message: "用户名必须是英文、数字或下划线组成",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]+$/,
            message: "密码必须是英文、数字或下划线组成",
            trigger: "blur",
          },
          { min: 5, message: "长度至少6位", trigger: "blur" },
        ],
        otp: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
      },
      loading: false,
      image: "",
    };
  },
  mounted() {
    this.setReqKaptcha();
    this.accountTip();
    this.createdCode()
  },
  methods: {
    submitForm(loginForm) {
      // 登录提交
      this.loading = true;
      this.$refs[loginForm].validate(async (valid) => {
        if (!valid) {
          this.$message.error("错了哦，请正确填写！");
          this.loading = false;
          return;
        }
        const { dispatch } = this.$store;

        dispatch("LoginByUsername", this.loginForm)
          .then((res) => {
            return dispatch("GetByToken");
          })
          .then((res) => {
            this.$router.push({ path: "/" });
            this.$message({ message: "登录成功", type: "success" });
          })
          .finally((_) => (this.loading = false))
          .catch(() => {
            this.setReqKaptcha();
          });
      });
    },
    setReqKaptcha() {
      // 获取图形验证码
      // getKaptcha().then(res => {
      //   this.image = res.data;
      // });
    },
    handleOpt() {
      // 重新获取图形验证码
      this.setReqKaptcha();
    },
      accountTip() {
      this.$notify({
        title: '管理员账号：admin02',
        dangerouslyUseHTMLString: true,
        message: '<strong>密码：<i>123456</i></strong>',
        type: 'success',
        position: 'bottom-left'
      })
      this.$notify({
        title: '商户账号：admim01',
        dangerouslyUseHTMLString: true,
        message: '<strong>密码：<i>123456</i></strong>',
        type: 'success',
        position: 'bottom-left',
        offset: 80
      })
    },

    // 验证码
     refreshCode () {
      this.createdCode()
    },
    createdCode () {
      let len = this.length,
        codeList = [],
        chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789',
        charsLen = chars.length
      // 生成
      for (let i = 0; i < len; i++) {
        let rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
        codeList.push({
          code: chars.charAt(Math.floor(Math.random() * charsLen)),
          color: `rgb(${rgb})`,
          fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
          padding: `${[Math.floor(Math.random() * 10)]}px`,
          transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
        })
      }
      // 指向
      this.codeList = codeList
      // 将当前数据派发出去
      this.$emit('update:value', codeList.map(item => item.code).join(''))
    },
    getStyle (data) {
      return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
    }
  },

};
</script>

<style lang="less" scoped>

    #login {
  width: 100%;
  height:100%;
  font-family: "Microsoft YaHei light", "微软雅黑", Arial, Tahoma, simhei,
  Helvetica, sans-serif;
  background: url("~@/assets/login_bg.png") no-repeat;
  background-size: 100% 100%;
  position: relative;
  .login_header {
    height: 80px;
    background-color: hsla(0, 0%, 100%, 0.2);
    text-align: center;
    line-height: 80px;
    .title {
      letter-spacing: 1px;
      font-size: 32px;
      margin: 0;
      margin-left: 20px;
      font-weight: bold;
      color: rgba(255, 255, 253, 1);
    }
  }
  .login_content {
    width: 400px;
    background-color: hsla(0, 0%, 100%, 1);
    padding: 20px 40px;
    box-sizing: border-box;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    h3 {
      text-align: center;
      font-size: 20px;
      font-weight: 700;
      margin-bottom: 20px;
    }
    .el-button {
      display: block;
      width: 100%;
      height: 40px;
      background: #6e90f7;
      border-radius: 4px;
      margin: 0 auto;
    }
    .el-button:hover {
      background: #3a68f3;
    }
    .kaptcha > .el-form-item__content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .el-input {
        width: 180px;
      }
      .kaptcha_img {
        display: block;
        width: 120px;
        height: 40px;
        float: right;
        img {
          width: 100%;
          height: 100%;
          cursor: pointer;
        }
      }
    }
  }
}


</style>